package main

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	var url string
	fmt.Scanln(&url)
	//url = "https://www.xbiquge.la/10/10489/"
	//创建客户端对象，发送请求
	var client = http.Client{}
	//发送请求
	req, _ := http.NewRequest("GET", url, nil)
	//req.Header.Set("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36")
	//发送请求
	// 发送请求
	resp, err := client.Do(req)
	// 处理异常
	if err != nil {
		fmt.Println("http get error", err)
		return
	}
	// 关闭流
	defer resp.Body.Close()
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	//书名
	bookNmae := doc.Find("h1").Text()
	fmt.Println(bookNmae)

	//创建导出文件
	file, err := os.Create(bookNmae+".txt")
	if err != nil {
		fmt.Println(err.Error())
	}
	defer file.Close()

	//写入书名
	file.WriteString(bookNmae+"\n")

	//作者
	authorNmae := doc.Find("h1").Next().Text()
	file.WriteString(authorNmae+"\n")

	doc.Find("#list>dl>dd").Each(func(i int, selection *goquery.Selection) {
		itemUrl,_ := selection.Find("a").Attr("href")

		//延时两秒
		time.Sleep(2*time.Second)
		//发送请求
		req, _ := http.NewRequest("GET", "https://www.xbiquge.la/"+itemUrl, nil)
		//req.Header.Set("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)")
		req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36")

		resp, err := client.Do(req)
		// 处理异常
		if err != nil {
			fmt.Println("http get error", err)
			return
		}
		// 关闭流
		defer resp.Body.Close()
		doc, err := goquery.NewDocumentFromReader(resp.Body)
		if err != nil {
			log.Fatal(err)
		}
		//写入章节名称
		chapterNmae := doc.Find("h1").Text()
		fmt.Println(chapterNmae)
		file.WriteString(chapterNmae+"\n")

		//写入章节内容
		contentTxt := doc.Find("#content").Text()
		file.WriteString(contentTxt)

	})

	fmt.Print("程序执行完毕，请查看结果。")
}